import { Module } from 'vuex'
import { RootState } from '../types'
import request from '@/utils/request'

interface UserState {
  token: string
  user: any
}

const userModule: Module<UserState, RootState> = {
  namespaced: true,

  state: {
    token: localStorage.getItem('token') || '',
    user: null
  },

  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    SET_USER(state, user) {
      state.user = user
    },
    CLEAR_USER(state) {
      state.token = ''
      state.user = null
      localStorage.removeItem('token')
    }
  },

  actions: {
    async login({ commit }, loginData) {
      const response = await request.post('/auth/login', loginData)
      const { token, username, role } = response.data
      commit('SET_TOKEN', token)
      commit('SET_USER', { username, role })
      return response.data
    },

    async register(_, registerData) {
      return await request.post('/auth/register', registerData)
    },

    async logout({ commit }) {
      commit('CLEAR_USER')
    }
  }
}

export default userModule 